﻿namespace BathroomLocator.Services.Infrastructure
{
	using System;
	using System.Globalization;
	using System.Web;
	using System.Web.Security;
	using BathroomLocator.Services.MembershipWrappers;

	public class StorageRequestValidator : IStorageRequestValidator
	{
		public StorageRequestValidator() :
			this(new RoleProviderWrapper(), new FormsAuthenticationService())
		{
		}

		public StorageRequestValidator(RoleProvider roleProvider, IFormsAuthentication formsAuth)
		{
			this.RoleProvider = roleProvider;
			this.FormsAuth = formsAuth;
		}

		public RoleProvider RoleProvider { get; private set; }

		public IFormsAuthentication FormsAuth { get; private set; }

		public bool ValidateRequest(HttpContext context)
		{
			var userName = this.GetUserName(context);

			if (string.IsNullOrEmpty(userName))
			{
				return false;
			}

			if (!this.CanUseTables(userName))
			{
				context.Response.EndWithDataServiceError(401, "Unauthorized", "You have no permission to use tables.");
			}

			var table = StorageRequestAnalyzer.GetRequestedTable(context.Request);

			if (!this.CanUseTable(userName, table))
			{
				context.Response.EndWithDataServiceError(401, "Unauthorized", "You have no permission to use this table.");
			}

			return true;
		}

		public string GetUserName(HttpContext context)
		{
			string ticketValue = null;

			var cookie = context.Request.Cookies[this.FormsAuth.FormsCookieName];

			if (cookie != null)
			{
				// From cookie
				ticketValue = cookie.Value;
			}
			else if (context.Request.Headers["AuthToken"] != null)
			{
				// From http header
				ticketValue = context.Request.Headers["AuthToken"];
			}

			if (!string.IsNullOrEmpty(ticketValue))
			{
				FormsAuthenticationTicket ticket = null;

				try
				{
					ticket = this.FormsAuth.Decrypt(ticketValue);
				}
				catch (ArgumentException)
				{
					context.Response.EndWithDataServiceError(401, "Unauthorized", "The Authorization Token is no longer valid.");
				}

				if (ticket != null)
				{
					return new FormsIdentity(ticket).Name;
				}
			}

			context.Response.EndWithDataServiceError(404, "Not Found", "Resource Not Found.");

			return string.Empty;
		}

		public bool CanUseTable(string userName, string tableName)
		{
			if (!tableName.Equals("Tables", StringComparison.OrdinalIgnoreCase))
			{
				var accessRole = string.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, RoleConstants.TableRoleSuffix);
				var publicAccessRole = string.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, RoleConstants.PublicTableRoleSuffix);

				if (!this.RoleProvider.RoleExists(publicAccessRole))
				{
					if (this.RoleProvider.RoleExists(accessRole))
					{
						if (!this.RoleProvider.IsUserInRole(userName, accessRole))
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
			}

			return true;
		}

		public bool CanUseTables(string userName)
		{
			return this.RoleProvider.IsUserInRole(userName, RoleConstants.TablesUsageRole);
		}
	}
}